<?php
include_once '../conn.php';

// 设置每页显示的游戏数量
$gamesPerPage = 6;

// 获取当前页数
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// 获取搜索关键词
$search = isset($_GET['search']) ? $_GET['search'] : '';

// 计算游戏总数和总页数
$queryCount = "SELECT COUNT(*) AS total FROM games WHERE title LIKE '%$search%'";
$resultCount = $conn->query($queryCount);
$rowCount = $resultCount->fetch_assoc();
$totalGames = $rowCount['total'];
$totalPages = ceil($totalGames / $gamesPerPage);

// 计算偏移量
$offset = ($page - 1) * $gamesPerPage;
 
// 查询游戏数据
$queryGames = "SELECT g.*, c.name AS category_name FROM games g LEFT JOIN categories c ON g.category_id = c.category_id WHERE g.title LIKE '%$search%' LIMIT $offset, $gamesPerPage";
$resultGames = $conn->query($queryGames);

// 存储游戏数据和总页数
$data = [
    'games' => [],
    'total_pages' => $totalPages,
];

// 将游戏数据添加到数组中
while ($rowGames = $resultGames->fetch_assoc()) {
    $data['games'][] = $rowGames;
}

// 将数据以 JSON 格式返回给前端
header('Content-Type: application/json');
echo json_encode($data);

// 关闭数据库连接
$conn->close();
?>
